package com.tjshop.android.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tjshop.android.OrderActivity;
import com.tjshop.android.R;
import com.tjshop.android.adapter.CartGoodsListAdapter;
import com.tjshop.android.constants.UrlConfigs;
import com.tjshop.android.mcv.GlobeVars;
import com.tjshop.android.model.tj.json.CartModel;

public class FragmentCart extends Fragment implements OnClickListener,Handler.Callback,OnCheckedChangeListener {

	private RequestQueue mQueue;
	private Handler mHandler;
	List<CartModel> cartModels = new ArrayList<CartModel>();
	List<CartModel> editCartModels = new ArrayList<CartModel>();
	ListView goodList;
	CartGoodsListAdapter mAdapter;
	TextView allPrice,edit;
	CheckBox bAll;
	LinearLayout totalPrice;
	Button save,gotopay,delete;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mHandler = new Handler(this);
		View v = LayoutInflater.from(getActivity()).inflate(
				R.layout.activity_main_fragment_cart, null);
		allPrice = (TextView) v.findViewById(R.id.allprice);
		bAll = (CheckBox) v.findViewById(R.id.bAll);
		bAll.setOnCheckedChangeListener(this);
		totalPrice = (LinearLayout) v.findViewById(R.id.totalPrice);
		mQueue = Volley.newRequestQueue(getActivity());
		goodList = (ListView) v.findViewById(R.id.goodsList);
		edit = (TextView) v.findViewById(R.id.cart_edit);
		edit.setOnClickListener(this);
		save = (Button) v.findViewById(R.id.save);
		save.setOnClickListener(this);
		gotopay = (Button) v.findViewById(R.id.gotopay);
		gotopay.setOnClickListener(this);
		delete = (Button) v.findViewById(R.id.delete);
		delete.setOnClickListener(this);
		mQueue = Volley.newRequestQueue(getActivity());
		goodList = (ListView) v.findViewById(R.id.goodsList);
		/*
		 * View pengyouquan =
		 * v.findViewById(R.id.activity_main_fragment_discover_penyouquan);
		 * pengyouquan.setOnClickListener(this); initEntryItem(pengyouquan,
		 * "朋友圈", R.drawable.entry_pengyouquan_icon);
		 * 
		 * View people =
		 * v.findViewById(R.id.activity_main_fragment_discover_people);
		 * people.setOnClickListener(this); initEntryItem(people, "附近的人",
		 * R.drawable.entry_nearby_people);
		 */


		return v;
	}

	void initEntryItem(View entryContainer, String text, int iconId) {
		TextView leftText = (TextView) entryContainer
				.findViewById(R.id.entry_item_left_icon);
		leftText.setText(text);
		leftText.setCompoundDrawablesWithIntrinsicBounds(iconId, 0, 0, 0);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onPause() {
		super.onPause();

		boolean userVisibleHint = getUserVisibleHint();
		Log.w(FragmentCart.class.getSimpleName(), "onPause - userVisibleHint: "
				+ userVisibleHint);
	}

	@Override
	public void onResume() {
		super.onResume();

		getCartData();
	}

	private void getCartData() {

		StringRequest stringRequest = new StringRequest(Method.GET,
				UrlConfigs.URL_CART_LIST+"?t="+GlobeVars.token,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						JSONArray jsonU;
						try {
							ArrayList<CartModel> temp = new ArrayList<CartModel>();
							JSONObject obj = new JSONObject(response);
							if (obj.getInt("r") == 0) {
								jsonU = obj.getJSONArray("s");
								for (int i = 0; i < jsonU.length(); i++) {
									
									CartModel c = new CartModel();
									c.parse(jsonU.getJSONObject(i));
									temp.add(c);
								}
								if(temp.size() == cartModels.size()){
									for(int i = 0;i<temp.size();i++){
										if(!cartModels.contains(temp.get(i))){
											break;
										}
									}
									return;
								}
								cartModels = temp;
								editCartModels = temp;
								selected = new boolean[temp.size()];
								
								Message message = new Message();
								message.what = 2;
								mHandler.sendMessage(message);
							} else {
								Message message = new Message();
								message.what = 1;
								mHandler.sendMessage(message);
							}

						} catch (JSONException e) {
							Message message = new Message();
							message.what = 1;
							mHandler.sendMessage(message);
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Message message = new Message();
						message.what = 1;
						mHandler.sendMessage(message);

					}

				});

		mQueue.add(stringRequest);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cart_edit:
			if(edit.getText().toString().equals("编辑")){
				setEditMode();
			}else{
				completeEdit();
			}
			
			break;
		case R.id.save:
			break;
		case R.id.gotopay:
			Intent i = new Intent(getActivity(), OrderActivity.class);
			Bundle b = new Bundle();
			List<CartModel> temp = new ArrayList<CartModel>();
			for(int j = 0;j<selected.length;j++){
				if (selected[j]) {
					temp.add(cartModels.get(j));
				}
			}
			b.putSerializable("goodslist", (Serializable) temp);
			i.putExtras(b);
			getActivity().startActivity(i);
			break;
		case R.id.delete:
			deleteCartModel();
			break;
		default:
			break;
		}

	}

	
	private void deleteCartModel() {
		
	}

	private void setEditMode() {
		edit.setText("完成");
		totalPrice.setVisibility(View.GONE);
		gotopay.setVisibility(View.GONE);
		save.setVisibility(View.VISIBLE);
		delete.setVisibility(View.VISIBLE);
//		mAdapter = new CartGoodsListAdapter(getActivity(), cartModels, LayoutInflater.from(getActivity()),mHandler,selected,2);
//		goodList.setAdapter(mAdapter);
		mAdapter.setMode(2);
		mAdapter.notifyDataSetChanged();
	}
	private void completeEdit() {
		edit.setText("编辑");
		totalPrice.setVisibility(View.VISIBLE);
		gotopay.setVisibility(View.VISIBLE);
		save.setVisibility(View.GONE);
		delete.setVisibility(View.GONE);
		for(int i = 0;i<cartModels.size();i++){
			if(editCartModels.get(i).getNum() != cartModels.get(i).getNum()){
				commitData(editCartModels.get(i));
			}
		}
		cartModels = editCartModels;
		
//		mAdapter = new CartGoodsListAdapter(getActivity(), cartModels, LayoutInflater.from(getActivity()),mHandler,selected,1);
//		goodList.setAdapter(mAdapter);
		mAdapter.setMode(1);
		mAdapter.notifyDataSetChanged();
	}
	private void commitData(CartModel c){

		StringRequest stringRequest = new StringRequest(Method.GET,
				UrlConfigs.URL_DELETE_CART+"?t="+GlobeVars.token+"&gid="+c.getGid()+"&num="+c.getNum(),
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}

				});

		mQueue.add(stringRequest);
	}

	@Override
	public boolean handleMessage(Message arg0) {
		switch (arg0.what) {
		case 1:
			Toast.makeText(getActivity(), "获取数据失败", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(getActivity(), "获取数据成功", Toast.LENGTH_SHORT).show();
			initView();
			break;
		case 5:
			selected[(Integer) arg0.obj] = true;
			calculatePrice();
			break;
		case 6:
			selected[(Integer) arg0.obj] = false;
			calculatePrice();
			break;
		default:
			break;
		}
		return true;
	}

	private void calculatePrice() {
		float price = 0f;
		for(int i = 0;i<selected.length;i++){
			if(selected[i]){
				price+= cartModels.get(i).getPrice()*cartModels.get(i).getNum();
			}
		}
		
		allPrice.setText(price+"");
	}

	boolean selected[] = new boolean[10];
	private void initView() {
		mAdapter = new CartGoodsListAdapter(getActivity(), cartModels, LayoutInflater.from(getActivity()),mHandler,selected);
		goodList.setAdapter(mAdapter);
	}

	@Override
	public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
		if(arg1){
			for(int i = 0;i<selected.length;i++){
				selected[i] = true;
				
			}
			mAdapter.setSelected(selected);
			mAdapter.notifyDataSetChanged();
//			initView();
		}else{
			for(int i = 0;i<selected.length;i++){
				selected[i] = false;
				
			}
			mAdapter.setSelected(selected);
			mAdapter.notifyDataSetChanged();
			
//			initView();
		}
		edit.setText("编辑");
		calculatePrice();
	}

	




}
